package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.damain.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.mapper.EmployeeMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
   @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        Employee employee=employeeMapper.fingbyusername(username);
        //判断用户名是否为空
        if (employee != null) {
            //用户名不为空，则判断密码是否相等，密码采用MD5加密，之后判断相同
            String passwordMD5= SecureUtil.md5(password);
            if (StringUtils.equals(passwordMD5,employee.getPassword())){
                //密码相同，确认员工状态
                if (employee.getStatus().equals(Employee.STATUS_ENABLE)){
                    return ResultInfo.success(employee);
                }else {
                  return ResultInfo.error("用户已被禁用");
                }

            }else {
              return   ResultInfo.error("密码错误");
            }


        }else {
            return ResultInfo.error("用户名不存在");
        }
    }

    @Override
    public List<Employee> findbyname(String name) {
        return employeeMapper.fingbyname(name);
    }

    @Override
    public void save(Employee employee) {
        //接收参数，使用雪花算法生成唯一id
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //设置默认密码，加密
        employee.setPassword(SecureUtil.md5("123456"));
        //默认status值为激活状态
        employee.setStatus(1);
        //时间设置
//        employee.setUpdateTime(new Date());
//        employee.setCreateTime(new Date());
//        //操作人设置
//        employee.setUpdateUser(1L);
//        employee.setCreateUser(1L);
        //调用mapper
        employeeMapper.save(employee);

    }

    @Override
    public Employee fingbyid(long id) {
        return employeeMapper.findbyid(id);
    }
//更新
    @Override
    public void update(Employee employee) {
//        employee.setUpdateUser(1L);
//        employee.setUpdateTime(new Date());
        employeeMapper.update(employee);

    }


}
